package com.sumainfor.pc.gmio.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.pc.gmio.dao.QueryHousingMapper;
import com.sumainfor.pc.gmio.feign.BaseFeignZuul;
import com.sumainfor.pc.gmio.feign.BasePcMktFeign;
import com.sumainfor.pc.gmio.service.QueryHousingService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-03-07 10:07
 * 疑问房源服务
 */
@Service
public class QueryHousingServiceImpl implements QueryHousingService {

    @Autowired
    private QueryHousingMapper queryHousingMapper;

    @Autowired
    private BasePcMktFeign marketFeign;

    @Autowired
    private BaseFeignZuul feignZuull;

    /**
     * 查询表格数据
     *
     * @param state 状态
     * @return
     */
    @Override
    public JsonResult getTableList(Page page, Integer state) {
        IPage<Map<String, Object>> pageData = queryHousingMapper.selectTableList(page, state);
        pageData.setRecords(pageData.getRecords().stream().map(item -> {
            //查询房源信息
            JsonResult<Map<String, Object>> result = marketFeign.getHousingInfoById(MapUtils.getString(item, "HouInfoId"));
            if (result.isSuccess() == false) {
                throw new TCException("查询房源信息失败");
            }
            item.putAll(result.getResult());
            //查询发起人的姓名
            JsonResult<List<Map<String, Object>>> userListRes = feignZuull.getUserInfo(Arrays.asList(MapUtils.getString(item, "AppId")));
            if (userListRes.isSuccess() == false) {
                throw new TCException("查询用户信息失败");
            }
            if (CollectionUtils.isEmpty(userListRes.getResult())) {
                throw new TCException("查询用户信息失败");
            }
            String userName = (String) userListRes.getResult().get(0).get("username");
            String mobile = (String) userListRes.getResult().get(0).get("mobile");
            item.put("userName", userName);
            item.put("mobile", mobile);
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(pageData);
    }

    /**
     * 设置通知
     *
     * @param douId
     * @return
     */
    @Override
    public JsonResult setNotification(String douId) {
        int row = queryHousingMapper.updateNotificationStateus(douId);
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }

}
